package com.weike.wk_android.interceptor;

import android.util.Log;

import java.io.IOException;
import java.util.Locale;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * log拦截器
 */
public class LogInterceptor implements Interceptor {
    private String TAG = "OkHttp";

    @Override
    public Response intercept(Chain chain) throws IOException {
        // 获取request对象
        Request request = chain.request();
        // 打印请求request信息
        Log.e(TAG, "intercept: " + request.toString());

        long t1 = System.nanoTime();
        // 获取服务器响应信息
        Response response = chain.proceed(request);

        long t2 = System.nanoTime();

        // 打印请求的地址，响应时间及响应头信息
        Log.e(TAG,String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));

        MediaType type = response.body().contentType();
        String content = response.body().string();

        // 打印response内容
        Log.e(TAG, "response body:" + content);

        // 再次对response的内容进行封装
        return response.newBuilder()
                .body(ResponseBody.create(type, content))
                .build();
    }
}
